//
//  JKBrowserViewController.m
//  ZhiHuDaily
//
//  Created by albert on 16/8/19.
//  Copyright © 2016年 albert. All rights reserved.
//

#import "JKBrowserViewController.h"
#import "JKImageBrowserView.h"
#import "JKShareView.h"
#import "JKProgressHUD.h"
#import "NavBarView.h"
@import WebKit;

@interface JKBrowserViewController () <WKNavigationDelegate, WKUIDelegate>
/** webview */
@property (weak, nonatomic) WKWebView *webView;

/** 返回 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *backItem;

/** 刷新 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *refreshItem;

/** 上一页 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *preItem;

/** 下一页 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *forwardItem;

/** 分享 */
@property (weak, nonatomic) IBOutlet UIBarButtonItem *shareItem;

@property (weak, nonatomic) IBOutlet NSLayoutConstraint *ToolBarBottomCons;

@property (weak, nonatomic) IBOutlet UIToolbar *toolBar;

/** 网页标题 */
@property (nonatomic, copy) NSString *webTitle;

/** navBarView */
@property (nonatomic, weak) NavBarView *navBarView;

/** 旋转菊花 */
@property (nonatomic, weak) UIActivityIndicatorView *indicatorView;

/** 夜间模式遮盖view */
@property (nonatomic, weak) UIView *coverView;
@end

@implementation JKBrowserViewController
#pragma mark - 懒加载
- (WKWebView *)webView{
    if (!_webView) {
        // 解决内存泄露问题
        WKWebViewConfiguration*config = [[WKWebViewConfiguration alloc]init];
        config.selectionGranularity = WKSelectionGranularityCharacter;
        
        // 让网页内容自适应大小
        NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);";
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        WKUserContentController *wkUController = [[WKUserContentController alloc] init];
        [wkUController addUserScript:wkUScript];
        config.userContentController = wkUController;
        
        // 创建WKWebView
        WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:config];
        if ([webView respondsToSelector:@selector(setAllowsLinkPreview:)]) {
            webView.allowsLinkPreview = YES;
        }
        webView.frame = CGRectMake(0, (JKBarHeight + JKStatusBarHeight), JKScreenW, JKScreenH - (JKBarHeight + JKStatusBarHeight) - JKBarHeight - self.view.jk_bottomSafeAreaView.height);
        webView.navigationDelegate = self;
        webView.UIDelegate = self;
        
        [self.view insertSubview:webView atIndex:0];
        _webView = webView;
    }
    return _webView;
}

- (UIView *)coverView{
    if (!_coverView) {
        UIView *coverView = [[UIView alloc] init];
        coverView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0.5];
        coverView.userInteractionEnabled = NO;
        [self.view addSubview:coverView];
        _coverView = coverView;
    }
    return _coverView;
}

#pragma mark - 生命周期方法
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateSkin) name:JKSkinModelDidChangedNotification object:nil];
    [self updateSkin];
}

#pragma mark - 初始化
- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self setup];
    
    self.view.jk_bottomSafeAreaView.backgroundColor = nil;
    UIToolbar *tbar = [[UIToolbar alloc] init];
    tbar.frame = self.view.jk_bottomSafeAreaView.bounds;
    tbar.backgroundColor = self.toolBar.backgroundColor;
    
    self.ToolBarBottomCons.constant = JKIsIphoneX ? JKHomeIndicatorHeight : 0;
}

- (void)setup{
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    
    // 导航条View
    NavBarView *navBarView = [NavBarView barView];
    [navBarView deleteBackButtonTitle];
    __weak typeof(self) weakSelf = self;
    [navBarView setBackBtnClickBlock:^(UIButton *button) {
        [weakSelf.navigationController popViewControllerAnimated:YES];
    }];
    [self.view addSubview:navBarView];
    self.navBarView = navBarView;
    navBarView.title = @"跳转中...";
    [self.webView loadRequest:self.request];
    
    // 旋转菊花
    UIActivityIndicatorView *indicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:(UIActivityIndicatorViewStyleWhite)];
    indicatorView.x = navBarView.width - 30;
    indicatorView.centerY = navBarView.defaltCenter.y;
    [navBarView addSubview:indicatorView];
    self.indicatorView = indicatorView;
}

- (void)viewDidLayoutSubviews{
    self.coverView.frame = self.webView.frame;
}

/** 返回 */
- (IBAction)backItemClick:(id)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

/** 刷新 */
- (IBAction)refreshItemClick:(id)sender {
    [self.webView reload];
}

/** 上一页 */
- (IBAction)preItemClick:(id)sender {
    [self.webView goBack];
}

/** 下一页 */
- (IBAction)forwardItemClick:(id)sender {
    [self.webView goForward];
}

/** 分享 */
- (IBAction)shareItemClick:(id)sender {
    NSString *url = self.webView.URL.absoluteString;
    [JKShareView showWithShareUrl:url title:self.webTitle];
}

- (void)dealloc{
    
    self.webView.scrollView.delegate = nil;
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

#pragma mark - <UIWebViewDelegate>
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation{
    [self.indicatorView startAnimating];
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.indicatorView stopAnimating];
    
    self.webTitle = webView.title;//[self.webView stringByEvaluatingJavaScriptFromString:@"document.title"];
    self.navBarView.title = self.webTitle;
    
    self.preItem.enabled = self.webView.canGoBack;
    self.forwardItem.enabled = self.webView.canGoForward;
    [self getImageUrlsViaJs];
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
    [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
    [self.indicatorView stopAnimating];
    //[JKProgressHUD showErrorWithStatus:@"加载失败！"];
    JKLog(@"%@", error);
}

//这里是js，主要目的实现对url的获取
- (void)getImageUrlsViaJs{
    //添加图片可点击js
    [self.webView evaluateJavaScript:@"function registerImageClickAction(){\
     var imgs=document.getElementsByTagName('img');\
     var length=imgs.length;\
     for(var i=0;i<length;i++){\
     img=imgs[i];\
     img.onclick=function(){\
     window.location.href='image-preview:'+this.src}\
     }\
     }" completionHandler:nil];
    [self.webView evaluateJavaScript:@"registerImageClickAction();" completionHandler:nil];
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
    //预览图片
    if ([navigationAction.request.URL.scheme isEqualToString:@"image-preview"]) {
        
        NSString* path = [navigationAction.request.URL.absoluteString substringFromIndex:[@"image-preview:" length]];
        
        //path 就是被点击图片的url
        //path = [path stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
        path = [path stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
        
        [JKImageBrowserView showWithImageUrlStr:path];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        
    }else if (![navigationAction.request.URL.scheme isEqualToString:@"http"] && ![navigationAction.request.URL.scheme isEqualToString:@"https"]) {
        
        if ([[UIApplication sharedApplication] canOpenURL:navigationAction.request.URL]) {
            
            [[UIApplication sharedApplication] openURL:navigationAction.request.URL];
        }
        
        decisionHandler(WKNavigationActionPolicyCancel);
        
    }else{
        
        decisionHandler(WKNavigationActionPolicyAllow);
    }
}

-(WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}

#pragma mark - 更新皮肤
- (void)updateSkin{
    NSString *currentSkinModel = [[NSUserDefaults standardUserDefaults] objectForKey:JKCurrentSkinModelKey];
    
    if ([currentSkinModel isEqualToString:JKNightSkinModelValue]) { // 夜间模式
        [self.navBarView changeToNightSkin];
        self.coverView.hidden = NO;
        
    }else{ // 日间模式
        [self.navBarView changeToDaySkin];
        self.coverView.hidden = YES;
    }
}
@end
